package com.softer.chengxin.project.service.impl;

import com.softer.chengxin.common.domin.*;
import com.softer.chengxin.common.enums.NumberEnum;
import com.softer.chengxin.common.enums.ResultEnum;
import com.softer.chengxin.common.util.GetDifferenceUtil;
import com.softer.chengxin.corp.dao.CorpDao;
import com.softer.chengxin.corp.domin.Corp;
import com.softer.chengxin.modify.dao.CompanyModifyDao;
import com.softer.chengxin.modify.entity.BaseModifyDetail;
import com.softer.chengxin.modify.entity.CompanyModify;
import com.softer.chengxin.modify.service.impl.ModifyServiceImpl;
import com.softer.chengxin.person.dao.PersonDao;
import com.softer.chengxin.project.dao.FeeDao;
import com.softer.chengxin.project.dao.ProjectDao;
import com.softer.chengxin.project.domin.ProfitVO;
import com.softer.chengxin.project.domin.Project;
import com.softer.chengxin.project.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gong Zhiyang
 * @date 2018/9/27
 */
@Slf4j
@Service
public class ProjectServiceImpl implements ProjectService {
    @Autowired
    private ProjectDao projectDao;
    @Autowired
    private PersonDao personDao;
    @Autowired
    private FeeDao feeDao;
    @Autowired
    private CorpDao corpDao;
    @Autowired
    private CompanyModifyDao companyModifyDao;
    @Autowired
    private ModifyServiceImpl modifyService;
    /**
     * 查询项目列表
     *
     * @param id        企业ID
     * @param projectId 项目ID
     * @return 项目列表
     */
    @Override
    public List<Project> queryProjectList(Integer id, String projectId) {
        return projectDao.queryProjectList(id, projectId);
    }

    /**
     * 删除项目
     *
     * @param id 项目ID
     * @return 结果
     */
    @Override
    public CommonResult delete(Integer id) {
        int num = projectDao.delete(id);
        if (num > Integer.parseInt(Common.ZERO)) {
            //删除项目人员
            personDao.deleteProjectPerson(id);
            return new CommonResult(ResultEnum.SUCCESS.getCode(), "删除成功");
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), "删除失败");
    }

    /**
     * 提交项目
     *
     * @param id 项目ID
     * @return 结果
     */
    @Override
    public CommonResult submit(Integer id) {
        Project project = detail(id);
        if (project == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "提交失败");
        }
        //查询项目经营情况是否填写完成
        if (StringUtils.isBlank(project.getDistrict())) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "提交失败,请完善项目信息");
        }
        ProfitVO profitVO = projectOperation(project.getProjectId());
        if (profitVO == null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "提交失败,请完善项目经营情况信息");
        }
        String state = "1";
        //区分区域信息
        //状态（0保存，1提交审核，2市审核通过，3审核不通过，4区审核通过（市审核中）） 5社区审核中 6街道审核中
        //开发区并且不为开发区的其他社区  状态为社区审核中
        if (String.valueOf(Common.FIVE).equals(project.getDistrict())) {
            String community = project.getCommunity();
            //开发区的提交单独处理
            if (StringUtils.isBlank(community) || Common.ZERO.equals(community) || "519".equals(community) || "520".equals(community) || "521".equals(community)) {
                // 如果社区为空，或者为开发区的‘其他’社区，则街道审核
                state = "6";
            } else {
                //存在社区且不为‘其他’社区的，社区审核
                state = "5";
            }
        }
        int num = projectDao.submit(state, id);
        if (num > Integer.parseInt(Common.ZERO)) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), "提交成功");
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), "提交失败");
    }

    /**
     * 查询项目信息列表
     *
     * @param page    页面实体
     * @param project 查询实体
     * @return 列表
     */
    @Override
    public ManagerPageResult query(Page page, Project project) {
        ManagerPageResult mr = new ManagerPageResult();
        JsonResult jr = new JsonResult();
        String states = "";
        if (Common.ADD.equals(project.getType())) {
            //信息录入页面（查询保存的，审核通过,审核不通过的项目信息）
            states = "0,3";
        } else if (Common.QUERY.equals(project.getType())) {
            //信息查询页面（查询审核中，审核通过项目信息）
            states = "1,2,4,5,6";
        }
        int num = projectDao.queryNum(project, states);
        if (num > Integer.parseInt(Common.ZERO)) {
            List<Project> list = projectDao.queryList(page, project, states);
            return setResult(mr, jr, num, list);
        }
        return setResult(mr, jr, Integer.parseInt(Common.ZERO), new ArrayList());
    }

    /**
     * 增加项目信息
     *
     * @param project 项目实体
     * @return 增加结果
     */
    @Override
    public CommonResult add(Project project) {
        if (StringUtils.isBlank(project.getProjectName())) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "请添加项目名称");
        }
        if (StringUtils.isBlank(project.getProjectId())) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "请添加项目ID");
        }
        Integer id = projectDao.getProjectId(project.getProjectId());
        if (id != null) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "添加项目失败，请稍后重试");
        }
        String projectName = projectDao.checkProjectName(project);
        if (StringUtils.isNotBlank(projectName)) {
            return new CommonResult(ResultEnum.FAIL.getCode(), "该项目已经添加过");
        }
        int num = projectDao.add(project);
        if (num > Integer.parseInt(Common.ZERO)) {
            return new CommonResult(ResultEnum.SUCCESS.getCode(), "新增成功", project.getId());
        }
        return new CommonResult(ResultEnum.FAIL.getCode(), "新增失败");
    }

    /**
     * 查询具体项目信息
     *
     * @param id 项目ID
     * @return 项目信息
     */
    @Override
    public Project detail(Integer id) {
        Project project = projectDao.detail(id);
        if (project != null) {
            String opinion = projectDao.queryProjectOpinion(id);
            project.setOpinion(opinion);
        }
        return project;
    }

    /**
     * 查询具体项目经营情况
     *
     * @param projectId 项目ID
     * @return 项目经营情况信息
     */
    @Override
    public ProfitVO projectOperation(String projectId) {
        ProfitVO projectOperation = feeDao.projectOperation(projectId);
        return projectOperation;
    }

    /**
     * 编辑项目信息
     *
     * @param project 项目实体
     * @return 编辑结果
     */
    @Override
    public CommonResult edit(Project project) {
        if (StringUtils.isBlank(project.getStreet())){
            return new CommonResult(ResultEnum.FAIL.getCode(), "请选择项目所在地");
        }
        //查询修改前状态，如果是‘审核失败’或者‘审核通过’，需要添加变更表
        Project detail = projectDao.detail(project.getId());
        if (detail != null && (NumberEnum.TWO.getNum().equals(detail.getState()) || NumberEnum.THREE.getNum().equals(detail.getState()))) {
            //查询是否存在待审核变更
            CompanyModify companyModify = companyModifyDao.getInfo(detail.getId());
            //1,插入变更表
            companyModify = modifyService.insertModify(companyModify, detail.getId(), Common.ZERO);
            try {
                List<BaseModifyDetail> difference = GetDifferenceUtil.getDifference(detail, project);
                //2,处理变更详情
                modifyService.dealModifyDetail(difference, companyModify.getId());
            } catch (IllegalAccessException e) {
                log.error("修改项目信息异常:",e.getStackTrace());
            }
        }
        int num = projectDao.edit(project);
        return CommonResult.response(num);
    }

    /**
     * 获取企业下所有项目
     *
     * @param id 企业ID
     * @return 项目列表
     */
    @Override
    public List<Project> getAllProject(Integer id) {
        return projectDao.getAllProject(id);
    }

    /**
     * 项目下拉列表，用于人员调动
     *
     * @param id        企业ID
     * @param projectId 项目ID
     * @return 项目列表
     */
    @Override
    public List<Project> getProjectListForPerson(Integer id, String projectId) {
        Corp corpInfo = corpDao.getCorpInfo(id);
        Project project = new Project();
        project.setId(0);
        project.setProjectName(corpInfo.getName());
        List<Project> list = projectDao.getProjectListForPerson(id, projectId);
        list.add(0, project);
        return list;
    }
    /**
     * 查询项目
     *
     * @param id 企业ID
     * @return
     */
    @Override
    public List<Project> selectAllProject(Integer id) {
        return projectDao.selectAllProject(id);
    }

    /**
     * 设置返回参数
     *
     * @param mpr  ManagerPageResult
     * @param jr   JsonResult
     * @param num  数量
     * @param list 集合列表
     */
    private ManagerPageResult setResult(ManagerPageResult mpr, JsonResult jr, int num, List list) {
        mpr.setCount(num);
        jr.setDs(list);
        mpr.setJson(jr);
        return mpr;
    }
}
